package com.xianan.xuhui.netsecurityproject.interceptor;

import com.alibaba.fastjson.JSON;
import com.xianan.xuhui.netsecurityproject.domain.constant.AuthConst;
import com.xianan.xuhui.netsecurityproject.domain.token.WebSessionDto;
import com.xianan.xuhui.netsecurityproject.utils.DateUtil;
import com.xianan.xuhui.netsecurityproject.utils.WebSessionUtil;
import com.xianan.xuhui.netsecurityproject.utils.WebTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author xiaoli
 * @description TODO
 * @since 2025/3/25 1:29
 */
@Slf4j
@Component
public class WebTokenAuthInterceptor implements HandlerInterceptor {
    @Resource
    WebTokenUtil tokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //token校验开关
        /*if (!tokenSwitch) {
            return true;
        }*/
        // 从请求头中获取用户token
        String token = request.getHeader(AuthConst.WEB_HEAD_KEY);
        log.info("Web Authorization token:" + token);
        log.info("Web Authorization request url:" + request.getRequestURI());
        String uri = request.getRequestURI();
        // 用户未登录，拦截请求
        if (StringUtils.isEmpty(token)) {
            // 状态设置为401
            response.setStatus(401);
            return false;
        }
        if (!tokenUtil.verifyToken(token)) {
            // 状态设置为401
            response.setStatus(401);
            return false;
        }

        WebSessionDto webSessionDto = tokenUtil.getTokenUser(token);
        Date lastTime = webSessionDto.getLastTime();
        Date currDate = DateUtil.getCurrDate();
        if(null!=lastTime){
            if(DateUtil.getDiffMinute(lastTime,currDate)>5){
                //和上次刷新session间隔超过5分钟，刷新session，延长token时间。设置间隔防止频繁刷redis
                webSessionDto.setLastTime(currDate);
                tokenUtil.refreshToken(webSessionDto,token);
            }
        }
        // 放入本地线程
        WebSessionUtil.set(webSessionDto);
        log.info("user session is :" + JSON.toJSONString(webSessionDto));
        return true;
    }

}
